//
//  InputToolHelperClass.m
//  RomensUISDK
//
//  Created by 裴飞杨 on 2017/7/22.
//  Copyright © 2017年 Romens. All rights reserved.
//

#import "InputToolHelperClass.h"
#import "RomensSDK/ActionSheetContentModel.h"

//解析服务器返回的参数
#define TEMPLATES       @"templates"
#define PAGENAME        @"group"
#define STATE           @"state"    //是否可以编辑


//一级
#define ID              @"ID"
#define CODE            @"code"
#define NAME            @"name"
#define UPDATEFUNC      @"updateFunc"
#define UPDATEPARAMS    @"updateParams"
#define NODES           @"nodes"
#define DATA            @"data"

//二级
#define KEY             @"key"         //KEY
#define CAPTION         @"caption"     //标题
#define INPUTTYPE       @"inputtype"   //类型
#define DEFAULVALUE     @"DefaultInputValue"    //默认值
#define HIDDEN          @"hidden"      //隐藏
#define COMBINVALUE     @"CombinValue" //选择项
#define MINVALUE        @"MinValue"    //最小值
#define MAXVALUE        @"MaxValue"    //最大值
#define RELATION        @"Relation"    //关系
#define FORMAT          @"FORMAT"      //格式化
#define ISLOCK          @"ISLOCK"      //锁定
#define FORMULA         @"FORMULA"     //公式
#define REFERENCE       @"REFERENCE"   //引用列
#define ISMUST          @"IsMust"      //必填项
#define ISHIGHLIGHT     @"HIGHTLIGHT"  //是否高亮
#define MAXLENGTH       @"MAXLENGTH"   //最大录入长度
#define MINLENGTH       @"MINLENGTH"   //最小录入长度
#define DECIMALPLACE    @"DecimalPlace"//小数部分保留位数
//数据选择用到的字段
#define SOURCE_HANDLER   @"HANDLER"   //数据选择Handle
#define SOURCE_QUERYTYPE @"QUERYTYPE" //数据选择方法名
#define SOURCE_CALLBACK  @"CALLBACK"  //数据选择后需要刷新项

#define DATA_SELECT     @"DATASELECT" //下一页请求方法参数等
//检测输入的特殊字符相关
#define INPUTTEXT_SPECIALEXP @"SPECIALEXP" //正则表达式
#define INPUTTEXT_SPECIAL @"SPECIAL"

@implementation InputToolHelperClass

#pragma mark -
#pragma mark ---- 解析数据 ----
#pragma mark -

#pragma mark -Type
+(InputDataModel *)handleInputDataWithObj:(id)dataObj {
    InputDataModel *dataModel = [[InputDataModel alloc] init];
    if (!dataObj) {
        return dataModel;
    }
    //解析不同类型的数据
    if ([dataObj isKindOfClass:[NSDictionary class]]) {
        if (((NSDictionary *)dataObj).allKeys.count == 0) {
            return dataModel;
        }
        dataModel = [self handleDataDict:(NSDictionary *)dataObj];
        dataModel.modelType = DataModelType1;

    } else if ([dataObj isKindOfClass:[NSArray class]]) {
        if (((NSArray *)dataObj).count == 0) {
            return dataModel;
        }
        dataModel.modelType = DataModelType2;
        dataModel.dataModels = [[NSMutableArray alloc] init];
        for (NSDictionary *tempDic in dataObj) {
            InputDataModel *tempDataModel = [self handleDataDict:(NSDictionary *)tempDic];
            //页码
            if ([tempDic objectForKey:PAGENAME]) {
                tempDataModel.pageName = tempDic[PAGENAME];
            }
            [dataModel.dataModels addObject:tempDataModel];
        }
    }
    return dataModel;
}
#pragma mark -权限、默认值处理
+(InputDataModel *)handleDataDict:(NSDictionary *)dataObj {
    InputDataModel *dataModel = [[InputDataModel alloc] init];
    //获取templates 数组对象
    if (![dataObj objectForKey:TEMPLATES] || !dataObj[TEMPLATES]) {
        return dataModel;
    }
    id templatesObj = dataObj[TEMPLATES];
    if (![templatesObj isKindOfClass:[NSArray class]]) {
        return dataModel;
    }

    NSArray *templates = (NSArray *)templatesObj;
    if (templates.count == 0) {
        return dataModel;
    }
    //获取编辑权限
    NSString *editStr = isEmptyString(dataObj[STATE])? @"0": dataObj[STATE];
    dataModel.editInput = [editStr boolValue];
    dataModel.templates = [[NSMutableArray alloc] init];
    //解析第一层
    int i = 0;
    for (NSDictionary *tempDic in templates) {
        InputSectionModel *sectionModel = [self handleTemplatesData:tempDic];
        [[dataModel mutableArrayValueForKey:ObserverKey] addObject:sectionModel];
        //解析第二层 Nodes
        NSArray *nodes = tempDic[NODES];
        if ([nodes isKindOfClass:[NSArray class]]) {
            sectionModel.nodes = [[NSMutableArray alloc] init];
            for (NSDictionary *nodeDic in nodes) {
                InputCellModel *cellModel = [self handleNodesData:nodeDic];
                //获取默认值
                NSString *key = [ToolHelper isEmptyStr:nodeDic[KEY]];
                cellModel.codeKey = key;
                if (sectionModel.dataDic && [sectionModel.dataDic objectForKey:key]) {
                    NSString *detailStr = [ToolHelper isEmptyStr:sectionModel.dataDic[key]];
                    //data中该项值为空时，不覆盖DefaultInputValue的值
                    if (!isEmptyString(detailStr)) {
                        if ([cellModel.inputtype isEqualToString:MLOOKUP_TYPE] || [cellModel.inputtype isEqualToString:LOOKUP_TYPE]) {
                            //自定义选择默认值
                            cellModel.combinDetail = detailStr;
                            cellModel.inputDetail = [self customPickDefaultValue:cellModel WithDetail:detailStr];
                            
                        } else {
                            //普通默认值
                            cellModel.inputDetail = detailStr;
                        }
                    }
                }
                [[sectionModel mutableArrayValueForKey:@"nodes"] addObject:cellModel];
            }
        }
        //除了第一列，其他都折行
        if (!sectionModel.nodes || i != 0) {
            sectionModel.close = YES;
        }
        i += 1;
    }
    return dataModel;
}
#pragma mark -解析第一层 Templates
+(InputSectionModel *)handleTemplatesData:(NSDictionary *)tempDic {
    InputSectionModel *sectionModel = [[InputSectionModel alloc] init];
    sectionModel.idString    = [ToolHelper isEmptyStr:tempDic[ID]];
    sectionModel.codeKey     = [ToolHelper isEmptyStr:tempDic[CODE]];
    sectionModel.nameCaption = [ToolHelper isEmptyStr:tempDic[NAME]];
    sectionModel.updateFunc  = [ToolHelper isEmptyStr:tempDic[UPDATEFUNC]];
    //获取默认值
    id dataDict = tempDic[DATA];
    if (dataDict && [dataDict isKindOfClass:[NSDictionary class]]) {
        sectionModel.dataDic = (NSDictionary *)dataDict;
    }
    //保存不带@的参数(供保存数据使用)
    NSString *paramStr = [ToolHelper isEmptyStr:tempDic[UPDATEPARAMS]];
    sectionModel.updateParams = paramStr;
    if (!isEmptyString(paramStr)) {
        NSArray *params = [paramStr componentsSeparatedByString:@","];
        sectionModel.updateParamsArray = [[NSMutableArray alloc] init];
        for (NSString *param in params) {
            if (![param hasPrefix:@"@"]) {
                [sectionModel.updateParamsArray addObject:param];
            }
        }
    }
    return sectionModel;
}
#pragma mark -解析第二层 Nodes
+(InputCellModel *)handleNodesData:(NSDictionary *)nodeDic {
    InputCellModel *cellModel = [[InputCellModel alloc] init];
    cellModel.nameCaption = [ToolHelper isEmptyStr:nodeDic[CAPTION]];
    //输入类型
    NSString *inputType = [ToolHelper isEmptyStr:nodeDic[INPUTTYPE]];
    cellModel.inputtype = inputType;
    //是否隐藏
    cellModel.ishidden = [[ToolHelper isEmptyStr:nodeDic[HIDDEN]] boolValue];// cellModel.hiddenStr = CellNotHidden;
    //是否锁定
    cellModel.isLock = [[ToolHelper isEmptyStr:nodeDic[ISLOCK]] boolValue];
    //必填项
    cellModel.isMustInput = [[ToolHelper isEmptyStr:nodeDic[ISMUST]] boolValue];
    //高亮
    cellModel.isHighlight = [[ToolHelper isEmptyStr:nodeDic[ISHIGHLIGHT]] boolValue];
    //输入的最小大值
    cellModel.minValue = [ToolHelper isEmptyStr:nodeDic[MINVALUE]];
    //输入的最大值
    cellModel.maxValue = [ToolHelper isEmptyStr:nodeDic[MAXVALUE]];
    //输入文本的最大长度
    cellModel.maxLength = [ToolHelper isEmptyStr:nodeDic[MAXLENGTH]];//@"";
    //输入文本的最小长度
    cellModel.minLength = [ToolHelper isEmptyStr:nodeDic[MINLENGTH]];
    //关系列
    cellModel.relation = [ToolHelper isEmptyStr:nodeDic[RELATION]];
    //字符串格式化规则
    cellModel.formatString = [ToolHelper isEmptyStr:nodeDic[FORMAT]];
    cellModel.inputFormat = [self receiveForamtWithString:[ToolHelper isEmptyStr:nodeDic[FORMAT]]];
    //公式
    cellModel.formula = [ToolHelper isEmptyStr:nodeDic[FORMULA]];
    //引用列
    cellModel.reference = [self stringSeparated:[ToolHelper isEmptyStr:nodeDic[REFERENCE]]];
    //特殊字符检测相关
    cellModel.textSpecialExp = [ToolHelper isEmptyStr:nodeDic[INPUTTEXT_SPECIALEXP]];
    cellModel.textSpecial = [ToolHelper isEmptyStr:nodeDic[INPUTTEXT_SPECIAL]];
    //小数部分长度
    cellModel.decimalPlace = [ToolHelper isEmptyStr:nodeDic[DECIMALPLACE]];
        //输入文本
    if ([inputType isEqualToString: TEXT_TYPE]) {
        cellModel.cellIdentifier = OneLineCellIdentifier;
        //输入多行文本
    }else if ([inputType isEqualToString: TEXT_MULTI_TYPE]) {
        cellModel.cellIdentifier = MultiLineCellIdentifier;
        //输入整数
    } else if ([inputType isEqualToString:INT_TYPE]) {
        cellModel.cellIdentifier = OneLineCellIdentifier;
        cellModel.keyboardType = UIKeyboardTypeNumberPad;
        //输入小数
    } else if ([inputType isEqualToString: DECIMAL_TYPE]) {
        cellModel.cellIdentifier = OneLineCellIdentifier;
        cellModel.keyboardType = UIKeyboardTypeDecimalPad;
        //多项选择
    } else if ([inputType isEqualToString: MLOOKUP_TYPE]) {
        cellModel.cellIdentifier = MultiLineCellIdentifier;
        cellModel.items = [self handleLookupItemsData:[ToolHelper isEmptyStr:nodeDic[COMBINVALUE]]];
        //自定义单选
    } else if ([inputType isEqualToString: LOOKUP_TYPE]) {
        cellModel.cellIdentifier = OneLineCellIdentifier;
        cellModel.items = [self handleLookupItemsData:[ToolHelper isEmptyStr:nodeDic[COMBINVALUE]]];
        //选择日期
    } else if ([inputType isEqualToString: PICKDATE_TYPE]) {
        cellModel.cellIdentifier = OneLineCellIdentifier;
        cellModel.minValue = [self handleDateStrWithTimeInterval:[ToolHelper isEmptyStr:nodeDic[MINVALUE]]];
        cellModel.maxValue = [self handleDateStrWithTimeInterval:[ToolHelper isEmptyStr:nodeDic[MAXVALUE]]];
        //日期时间
    } else if ([inputType isEqualToString: DATETIME_TYPE]) {
        cellModel.cellIdentifier = MultiLineCellIdentifier;
        //switch
    } else if ([inputType isEqualToString: BOOL_TYPE]) {
        cellModel.cellIdentifier = SwitchCellIdentifier;
        cellModel.boolItems = [self stringSeparated:[ToolHelper isEmptyStr:nodeDic[COMBINVALUE]]];
        //数据选择
    }  else if ([inputType isEqualToString: DATASOURCE_TYPE]) {
        cellModel.cellIdentifier = MultiLineCellIdentifier;
        cellModel.sourceHandle = [ToolHelper isEmptyStr:nodeDic[SOURCE_HANDLER]];
        cellModel.sourceQueryType = [ToolHelper isEmptyStr:nodeDic[SOURCE_QUERYTYPE]];
        cellModel.sourceCallBack = [self stringSeparated:[ToolHelper isEmptyStr:nodeDic[SOURCE_CALLBACK]]];
        //数据集
    } else if ([inputType isEqualToString: DATADETAIL_TYPE]) {
        cellModel.cellIdentifier = MultiLineCellIdentifier;
        [self handleDataSelect:nodeDic withModel:cellModel];
        //省市区
    } else if ([inputType isEqualToString: REGION_TYPE]) {
        cellModel.cellIdentifier = MultiLineCellIdentifier;
    }
    
    //默认值
    NSString *defaultValue = [ToolHelper isEmptyStr:nodeDic[DEFAULVALUE]];
    cellModel.inputDetail = [self receiveDefaultInputValue:defaultValue cellModel:cellModel];
    
    return cellModel;
}
#pragma mark -
#pragma mark ---- 业务解析方法 ----
#pragma mark -

#pragma mark -DefaultInputValue
+(NSString *)receiveDefaultInputValue:(NSString *)value
                            cellModel:(InputCellModel *)cellModel
{
    if (isEmptyString(value)) {
        return @"";
    }
    NSString *type = cellModel.inputtype;
    //@XXX@格式的数据
    if ([value hasPrefix:@"@"] && [value hasSuffix:@"@"]) {
        NSString *defaultValue = [value stringByReplacingOccurrencesOfString:@"@" withString:@""];
        if ([defaultValue isEqualToString:CurrentDate]) {
            return [self handleDateStrWithTimeInterval:[ToolHelper GetTimeIntervalSinceFor10]];
        } else {
            return @"";
        }
    } else if ([type isEqualToString:LOOKUP_TYPE] || [type isEqualToString:MLOOKUP_TYPE]) {
        // 单选、多选 DefaultInputValue处理
        return [self customPickDefaultValue:cellModel WithDetail:value];
    }
    return value;
}
#pragma mark -单选、多选，'[XX,XX][XX,XX]'数据
+(NSMutableArray *)handleLookupItemsData:(NSString *)itemesStr {
    if (isEmptyString(itemesStr)) {
        return [[NSMutableArray alloc] init];
    }
    NSMutableArray *array = [self handleBracketData:itemesStr];
    NSMutableArray *items = [[NSMutableArray alloc] init];
    for (NSString *itemStr in array) {
        //截取
        NSArray *itemeData = [itemStr componentsSeparatedByString:@","];
        if (itemeData.count == 2) {
            //拼成字典
            ActionSheetContentModel *model = [[ActionSheetContentModel alloc] init];
            model.contentValue = itemeData[0];
            model.contentTitle = itemeData[1];
            model.isCheck = NO;
            [items addObject:model];
        }
    }
    return items;
}
#pragma mark -业务数据格式化规则
+(NSString *)receiveForamtWithString:(NSString *)format {
    if (isEmptyString(format)) {
        return NotFormat;
    }
    NSString *rangeStr = @"(?<=\\{).*(?=\\})";
    NSRange range = [format rangeOfString:rangeStr options:NSRegularExpressionSearch];
    NSString *str = [format substringWithRange:range];
    NSArray *values = [str componentsSeparatedByString:@"::"];
    if (values.count <= 1 || isEmptyString(values[1])) {
        return NormalFormat;
    } else {
        return values[1];
    }
}
#pragma mark -解析时间戳
+(NSString *)handleDateStrWithTimeInterval:(NSString *)timeString{
    if (isEmptyString(timeString)) {
        return @"";
    }
    NSDate *date = [ToolHelper GetTimeIntervalSinceFor10:timeString];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"YYYY年MM月dd日"];
    [formatter setTimeZone:timeZone];
    return [formatter stringFromDate:date];
}
#pragma mark -解析数据集数据 DATASELECT_TYPE使用
+(void)handleDataSelect:(NSDictionary *)dict withModel: (InputCellModel *)model {
    NSString *selectStr = [ToolHelper isEmptyStr:dict[DATA_SELECT]];
    NSMutableArray *selectArray = [self handleBracketData:selectStr];
    if (selectArray.count > 0) {
        NSArray *apiArray = [selectArray[0] componentsSeparatedByString:@"|@"];
        if (apiArray.count > 3) {
            if (![apiArray[0] isEqualToString:@"API"]) {
                return;
            }
            model.sourceHandle = apiArray[2];
            model.sourceQueryType = apiArray[1];
            model.parames = [apiArray[3] componentsSeparatedByString:@","];
        }
    }
    if (selectArray.count > 1) {
        NSArray *templateArray = [selectArray[1] componentsSeparatedByString:@"|@"];
        if (templateArray.count > 0) {
            if (![templateArray[0] isEqualToString:@"TEMPLATE"]) {
                return;
            }
            model.templateCode = templateArray[1];
        }
    }
    NSString *mainKeyStr = [ToolHelper isEmptyStr:dict[RELATION]];
    NSMutableArray *mainKeyArray = [self handleBracketData:mainKeyStr];
    if (mainKeyArray.count > 0) {
        NSArray *mainKeyData = [mainKeyArray[0] componentsSeparatedByString:@":"];
        if (![mainKeyData[0] isEqualToString:@"MAINKEY"]) {
            return;
        }
        model.mainKey = mainKeyData[1];
    }
}

#pragma mark -自定义选择的默认值
+(NSString *)customPickDefaultValue:(InputCellModel *)model WithDetail:(NSString *)detail {
    if (isEmptyString(detail)) {
        return @"";
    }
    NSArray *choseItems = nil;
    if ([detail containsString:@","]) {
        choseItems = [detail componentsSeparatedByString:@","];
    } else {
        choseItems = [[NSArray alloc] initWithObjects:detail, nil];
    }
    NSString *itemStr = @"";
    for (ActionSheetContentModel *content in model.items) {
        for (NSString *choseItem in choseItems) {
            if ([content.contentValue isEqualToString:choseItem]) {
                content.isCheck   = YES;
                if (isEmptyString(itemStr)) {
                    itemStr = content.contentTitle;
                } else {
                    itemStr = [itemStr stringByAppendingString:[NSString stringWithFormat:@", %@", content.contentTitle]];
                }
            }
        }
        
    }
    return itemStr;
}

#pragma mark -
#pragma mark ---- 解析工具方法 ----
#pragma mark -

#pragma mark -解析XX，XX数据
+(NSArray *)stringSeparated:(NSString *)str{
    if (isEmptyString(str)) {
        return [[NSArray alloc] init];
    }
    return [str componentsSeparatedByString:@","];
}

#pragma mark -解析[xxxx][xxxx]数据
+(NSMutableArray *)handleBracketData:(NSString *)str {
    if (isEmptyString(str)) {
        return nil;
    }
    NSString *rang = @"\\[[^\\]]*\\]";
    __block NSMutableArray *fields = [[NSMutableArray alloc] init];
    NSError *error = NULL;
    NSRegularExpression *fieldRegularExpression = [NSRegularExpression
                                                   regularExpressionWithPattern:rang
                                                   options:NSRegularExpressionCaseInsensitive
                                                   error:&error];
    [fieldRegularExpression enumerateMatchesInString:str
                                             options:0
                                               range:NSMakeRange(0, [str length])
                                          usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop)
    {
      if(match.range.length > 2) {
          //Remove '[' and ']'
          NSRange range = NSMakeRange(match.range.location + 1, match.range.length - 2);
          [fields addObject:[str substringWithRange:range]];
      }
    }];
    return fields;
}

#pragma mark -
#pragma mark ---- 对外开放的接口 ----
#pragma mark -

#pragma mark -解析{XX}数据
+(NSString *)handleFormatString:(NSString *)format {
    if (isEmptyString(format)) {
        return @"";
    }
    NSString *rangeStr = @"\\{.*\\}";
    NSRange range = [format rangeOfString:rangeStr options:NSRegularExpressionSearch];
    return [format substringWithRange:range];
}
#pragma mark -根据解析业务（type）规则（format）来解析（detail）
+(NSString *)formatInputDetailWithInputType:(NSString *)type
                                 WithDetail:(NSString *)detail
                                 WithFormat:(NSString *)format
{
    if (isEmptyString(detail)) {
        return @"";
    }
    if ([type isEqualToString:PICKDATE_TYPE]) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        NSDate *date;
        if ([detail isEqualToString:CurrentDate]) {
            date = [NSDate date];
        } else {
            NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
            [dateFormatter setTimeZone:timeZone];
            date =  [dateFormatter dateFromString:detail];
        }
        [dateFormatter setDateFormat:format];
        NSString *returnStr = [dateFormatter stringFromDate:date];
        return isEmptyString(returnStr)? detail: returnStr;
    }
    return @"";
}
#pragma mark -
#pragma mark ---- 模板操作 ----
#pragma mark -

#pragma mark -获取每条录入项的录入值
+(NSString *)selectNodeInputValue:(InputCellModel *)model {
    if (!model) {
        return @"";
    }
    NSString *detailStr = @"";
    if ([model.inputtype isEqualToString:MLOOKUP_TYPE] || [model.inputtype isEqualToString:LOOKUP_TYPE]) {
        detailStr = [ToolHelper isEmptyStr:model.combinDetail];
        
    } else if ([model.inputtype isEqualToString:BOOL_TYPE]) {
        detailStr = isEmptyString(model.inputDetail)? @"0": model.inputDetail;
        
    } else {
        detailStr = [ToolHelper isEmptyStr:model.inputDetail];
        
    }
    return detailStr;
}
#pragma mark -根据key获取录入的值
+(NSString *)selectNodeInputValue:(NSString *)nodeKey byTemplate:(InputSectionModel *)sectionModel {
    if (isEmptyString(nodeKey) || !sectionModel) {
        return @"";
    }
    for (InputCellModel *cellModel in sectionModel.nodes) {
        if ([cellModel.codeKey isEqualToString:nodeKey]) {
            return cellModel.inputDetail;
        }
    }
    return @"";
}
#pragma mark -根据nodeKey赋值
+(void)setupNodeInputValue:(NSString *)nodeKey nodeValue:(NSString *)nodeValue byTemplate:(InputSectionModel *)sectionModel {
    if (isEmptyString(nodeKey) || !sectionModel) {
        return;
    }
    for (InputCellModel *cellModel in sectionModel.nodes) {
        if ([cellModel.codeKey isEqualToString:nodeKey]) {
            cellModel.inputDetail = [ToolHelper isEmptyStr:nodeValue];
            break;
        }
    }
}

@end
//#pragma mark - 检测身份证号
//+(BOOL)isIdentityCard:(NSString *)IDCardNumber {
//    if (IDCardNumber.length <= 0) {
//        return NO;
//    }
//    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
//    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
//    return [identityCardPredicate evaluateWithObject:IDCardNumber];
//}
